<template>
  <a-upload :action="mAction" v-model:file-list="mFileList" :headers="mHeaders" @change="handleChange">
    <template v-for="item in slotKeys.filter(key => props[key])" #[item]="slotProps">
      <component :is="renderSlot(props,item,slotProps || {})" />
    </template>
    <template v-if="!props.isNoLogin">
      <a-button v-bind="{ ...btnProps }">{{ btnText }}</a-button>
    </template>
    <template v-if="props.isNoLogin">
      <a-button v-bind="{ ...btnProps }">{{ btnAimiText }}</a-button>
    </template>
  </a-upload>
</template>
<script setup lang="ts">
const slotKeys = ['default', 'itemRender', 'downloadIcon', 'removeIcon']
import { PropType, VNode, onMounted, ref, watch } from 'vue';
import { renderSlot } from '..';
import { useUserStore } from '/@/store/modules/user';
import { UploadFile } from 'ant-design-vue';
import request from '/@/utils/request'

const emits = defineEmits(['change', 'update:value'])
const props = defineProps({
  value: {
    type: String,
    default() {
      return true
    }
  },
  isNoLogin: {
    type: Boolean,
    default() {
      return true
    }
  },
  btnText: {
    type: String,
    default() {
      return '上传图片'
    }
  },
  btnAimiText: {
    type: String,
    default() {
      return '登录Aimi'
    }
  },
  btnProps: { // 按钮属性
    type: Object
  },
  default: {
    type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>,

  },
  itemRender: {
    type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
  },
  downloadIcon: {
    type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
  },
  removeIcon: {
    type: [String, Object, Function] as PropType<String | VNode | (() => VNode | String)>
  },
  action: {
    type: [Function, String] as PropType<((file: any) => Promise<any>) | String>,
    default() {
      return import.meta.env.VITE_APP_UPLOAD_URL
    }
  },
  headers: {
    type: Object
  },
  getFileInfoUrl: {
    type: String,
    default() {
      return import.meta.env.VITE_APP_GET_FILE_INFO_URL
    }
  }
})
/**
 * 获取默认的请求头
 */
const getDefaultHeades = () => {
  const userStore = useUserStore()
  const token = userStore.getAimiToken
  return {
    Authorization: 'Bearer ' + token,
    // 这里的tokenkey提供给apifox使用，后续再根据apifox条件追加
    token: 'Bearer ' + token,
  }
}
const mAction = ref()
const mHeaders = ref({
  ...getDefaultHeades(),
  ...props.headers
})
const mFileList = ref<Array<UploadFile>>([])
watch(() => props.action, () => {
  mAction.value = props.action as any
}, {
  deep: true
})
watch(() => props.headers, () => {
  mHeaders.value = {
    ...getDefaultHeades(),
    ...props.headers
  }
  console.log('props.headers---',props.headers);
  
}, {
  deep: true
})
watch(() => props.value, () => {
  fileInfoIdsToFileList(props.value)
}, {
  deep: true
})
let fileInfoMap = {}
const handleChange = (e: any) => {
  if (e.file.status == 'done') {
    // 上传完成
    const fileInfoId = e.file.response?.data?.fileInfoId
    fileInfoMap[e.file.uid] = fileInfoId
    emits('update:value', Object.keys(fileInfoMap).map(key => fileInfoMap[key]).join(","))
  } else if (e.file.status == 'removed') {
    delete fileInfoMap[e.file.uid]
    emits('update:value', Object.keys(fileInfoMap).map(key => fileInfoMap[key]).join(","))
  }
  emits('change', e)
}
/**-
 * 文件信息id转文件列表
 * @param fileInfoIds 
 */
const fileInfoIdsToFileList = (fileInfoIds: String | undefined) => {
  fileInfoMap = {}
  if (fileInfoIds) {
    request.post(props.getFileInfoUrl as string, {
      fileInfoIds
    }).then((res) => {
      const v = res.data || res
      if (v instanceof Array && v.length) {
        mFileList.value = v
        v.forEach(item => {
          fileInfoMap[item.uid] = item.id || item.uid
        })
      }
    })
  }
}
onMounted(() => {
  if (props.action && typeof props.action == 'string') {
    // mAction.value = `${import.meta.env.VITE_APP_API}${props.action}`
    mAction.value = `${import.meta.env.VITE_IMAGE_API}${props.action}`
    // console.log('mAction.value', mAction.value);
    console.log('props.isNoLogin----', props.isNoLogin);
    
  }
  fileInfoIdsToFileList(props.value)
})
</script>
<style lang="less" scoped></style>